<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="30%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="100px"
    >
      <el-form-item label="角色组名称" prop="roleGroupName">
        <el-input
          size="small"
          v-model="dataForm.roleGroupName"
          placeholder="角色组名称"
        />
      </el-form-item>
      <el-form-item v-if="false" label="角色名称" prop="roleName">
        <el-input
          size="small"
          v-model="dataForm.roleName"
          placeholder="角色名称"
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="visible = false">取消</el-button>
      <el-button size="small" type="primary" @click="dataFormSubmit"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { saveRole, updateRole } from "@/api/sys-role";
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: "",
        roleGroupName: "",
        roleName: "",
      },
      dataRule: {
        roleGroupName: [
          { required: true, message: "角色组名称不能为空", trigger: "blur" },
        ],
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    init(row) {
      Object.assign(this.$data, this.$options.data()); //清空组件状态
      this.visible = true;
      this.dataForm.id = row.id;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (!valid) return;
        if (this.dataForm.id === undefined) {
          // 保存角色信息 /nuwa-sys-role/saveRole
          saveRole(this.dataForm).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: "新增成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          // 修改角色信息 /nuwa-sys-role/updateRole
          updateRole(this.dataForm).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
  },
};
</script>
